<template>
  <div class="medical-record" >
    <div class="medical-head">
      <div class="head-left">
        <span :class="{'active-1': isActive === '病历档案'}" @click="switchBtn('病历档案')">病历档案</span>
        <!-- <span :class="{'active-1': isActive === '牙齿检查'}" @click="switchBtn('牙齿检查')">牙齿检查</span>
        <span :class="{'active-1': isActive === '牙周检查'}" @click="switchBtn('牙周检查')">牙周检查</span>
        <span :class="{'active-1': isActive === '治疗计划'}" @click="switchBtn('治疗计划')">治疗计划</span> -->
      </div>
      <div class="head-right">
        <!-- <div class="adjustment">
          <el-select v-if="isActive === '病历档案'" class="select-1" v-model="allTag"  placeholder="全部标签">
            <el-option
              v-for="item in allOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div> -->
        
        <el-button class="btn-1" v-if="isActive === '病历档案'" @click="handleAllParint">打印所有病历</el-button>
        <el-button class="btn-1" v-if="isActive === '病历档案' && !isAdd" @click="addRecord" v-jurisdiction="'customer:sick:history:add'">新建病历</el-button>
      </div>
    </div>
    <div class="medical-content" v-loading="loading">
      <div class="medical-one" v-if="isActive === '病历档案' && !isAdd">
        <recordlist ref="refRecordList" :id="id" @recordLength="recordLength"></recordlist>
      </div>
      
      <!-- 传送 -->
                <div>
                  <teleport to="body">
                    <!-- main-content -->
                    <tdialog ref="tDialogRef" :title="type" :isShow="isShow" @hideDialog="hideDialog"></tdialog>
                </teleport>
                </div>
                
      <!-- 新建病历 -->
      <template v-if="isAdd">
        
      
      <div class="medical-add" >
        <div class="title-border">
          <div class="title">
            <span>医生信息</span>
          </div>
          <div class="t-content">
            <div class="ware-type">
              <div class="type-title">医生</div>
              <el-select class="select-1" v-model="doctor" filterable placeholder="请选择">
                  <el-option
                    v-for="item in doctorOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
              </el-select>
            </div>
            <div class="ware-type">
              <div class="type-title">护士</div>
              <el-select class="select-1" v-model="nurse" filterable placeholder="请选择" >
                  <el-option
                    v-for="item in nurseOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
              </el-select>
            </div>
            <div class="ware-type">
              <div class="type-title" style="padding:0">就诊时间</div>
              <el-date-picker
                class="date-1"
                type="datetime"
                v-model="dateTime"
                placeholder="选择日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                >
            </el-date-picker>
            </div>
            <div class="ware-type">
              <div class="type-title">类型</div>
              <el-radio-group v-model="type" class="radio-group-2">
                <el-radio-button label="初诊">初诊病历</el-radio-button>
                <el-radio-button label="复诊">复诊病历</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </div>

        <div class="title-border">
          <div class="title">
            <span>病历信息</span>
          </div>
          <div class="t-content" ref="refContent">
            <div class="left-switch">
              <ul class="collapse">
                <li class="collapse-child" v-for="(item) in collapseData" :key="item.title">
                  <div class="open" @click="openChild(item)">
                  <el-icon v-if="item.isActive"><CaretBottom /></el-icon>
                  <el-icon v-else class="r90"><CaretBottom /></el-icon>
                    <span>{{item.title}}</span>
                  </div>
                  <ul :class="{'hide': item.isActive}">
                      <li @click="clickItem(c)" v-for="c in item.children" :key="c.id">
                        <!-- <a :href="'#' + c.id"> -->
                          <span>{{c.title}}</span>
                        <!-- </a> -->
                      </li>
                    
                  </ul>
                </li>
              </ul>
            </div>
            <div class="right-info">
                <div class="template-medical" @click="showDialog">
                  <span>病历模板</span>
                  <el-icon><arrow-down /></el-icon>
                </div>
                
                <!-- 选中模板回显数据 -->
                <div class="scrooll" ref="scrooll">
                  <zinput ref="zhusu" 
                    :title="'主诉'" @changValue="getZhusu" 
                    :textareaValue="zhusuVal" 
                    :tree-data="treeData"
                    ></zinput>
                  <zinput ref="xianbingshi" 
                    :title="'现病史'" @changValue="getXianbs" 
                    :textareaValue="xianbingshiVal" 
                    :tree-data="treeData"
                    ></zinput>
                  <zinput ref="jiwangsi" 
                    :title="'既往史'" @changValue="getjiwangs" 
                    :textareaValue="jiwangsiVal" 
                    :tree-data="treeData"
                    ></zinput>
                  <zcompose ref="kouqiangjiancha" :title="'口腔检查'"  
                            :tree-data="treeData"
                            :toothList="ToothList" 
                            @addToothPosition="addToothPosition(ToothList)" 
                            @handleDelete="handleDelete" 
                            @changValue="changValue"
                            @getLeftData="getLeftData"
                            @getRightData="getRightData"
                            @getLeftBottomData="getLeftBottomData"
                            @getRightBottomData="getRightBottomData"
                  ></zcompose>
                  <zcompose ref="fuzhujiancha" :title="'辅助检查'" 
                            :tree-data="treeData"
                            :toothList="ToothList1" 
                            @addToothPosition="addToothPosition(ToothList1)" 
                            @handleDelete="handleDelete"
                            @changValue="changValue1"
                            @getLeftData="getLeftData1"
                            @getRightData="getRightData1"
                            @getLeftBottomData="getLeftBottomData1"
                            @getRightBottomData="getRightBottomData1"
                            
                  ></zcompose>
                  <zcompose ref="zhenduan" :title="'诊断'" 
                            :tree-data="treeData"
                            :toothList="ToothList2" 
                            @addToothPosition="addToothPosition(ToothList2)" 
                            @handleDelete="handleDelete"
                            @changValue="changValue2"
                            @getLeftData="getLeftData2"
                            @getRightData="getRightData2"
                            @getLeftBottomData="getLeftBottomData2"
                            @getRightBottomData="getRightBottomData2"
                            
                  ></zcompose>
                  <zcompose ref="zhiliaojihua" :title="'治疗计划'" 
                            :tree-data="treeData"
                            :toothList="ToothList3" 
                            @addToothPosition="addToothPosition(ToothList3)" 
                            @handleDelete="handleDelete"
                            @changValue="changValue3"
                            @getLeftData="getLeftData3"
                            @getRightData="getRightData3"
                            @getLeftBottomData="getLeftBottomData3"
                            @getRightBottomData="getRightBottomData3"
                            
                  ></zcompose>
                  <zcompose ref="chuzhi" :title="'处置'" 
                            :tree-data="treeData"
                            :toothList="ToothList4" 
                            @addToothPosition="addToothPosition(ToothList4)" 
                            @handleDelete="handleDelete"
                            @changValue="changValue4"
                            @getLeftData="getLeftData4"
                            @getRightData="getRightData4"
                            @getLeftBottomData="getLeftBottomData4"
                            @getRightBottomData="getRightBottomData4"
                            
                  ></zcompose>
                  <zinput 
                    ref="yizhu" :title="'医嘱'"  
                    @changValue="getyizhu" :textareaValue="yizhuVal"
                    :tree-data="treeData"
                    ></zinput>
                  <span>标签</span>
                  <el-select multiple  style="width: 100%" v-model="label" placeholder="请选择" >
                      <el-option
                        v-for="item in labelList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                  </el-select>
                  <div>备注</div>
                  <el-input
                    type="textarea"
                    :rows="2"
                    placeholder="请输入内容"
                    v-model="remarks">
                  </el-input>
                </div>

                <!-- 按钮 -->
                <div class="main-foo">
                  <el-button class="btn-1" @click="save">保存</el-button>
                  <!-- <el-button class="btn-1" @click="cancel">取消</el-button> -->
                  <el-button class="btn-1" @click="addTemplate">另存为模板</el-button>
                </div>

                <zdialog 
                  @handleClose="closeDialog" 
                  v-model="dialogVisible" 
                  :btnData="btnData"
                  title="模板保存"
                  >
                <template #body>
                  <div class="temp-Type">
                    <div class="left-tree-Type">
                      <div class="tree-title">模板类别</div>
                      <div class="tree-mian">
                        <el-tree
                          :props="defaultProps"
                          :data="templateList"
                          @node-click="handleNode"
                          @node-contextmenu="handleNodeMenu"
                          >
                        </el-tree>
                      </div>
                      <div class="tree-footer" @click="addTemType('root')">
                          <el-icon><plus /></el-icon>
                          <span>添加根类型</span>
                      </div>
                    </div>
                    <div class="right-temp-content">
                        <div class="leftToRight-layout" style="width: auto;">
                          <div class="label f-14" style="width: auto;">
                            <span>模板名称</span>
                          </div>
                          <div class="operations">
                            <el-input
                              v-model="temTitle"
                              class="width200 input-1"
                              >
                            </el-input>
                          </div>
                        </div>
                        <div class="leftToRight-layout" style="width: auto;" v-for="(i, index) in temObj" :key="i.name">
                          <div class="label f-14" style="width: 75px;">
                            <span>{{i.name}}</span>
                          </div>
                          <div class="operations">
                            <el-input
                              type="textarea"
                              :rows="2"
                              v-model="i.value"
                              class="width200 input-1"
                              >
                            </el-input>
                          </div>
                        </div>
                    </div>
                  </div>
                    <!-- 右击提示操作框 -->
                  <div class="tipsOperation" ref="tipsOPerRef" v-show="menuVisbile">
                    <div class="tip-item" @click="addTemType('children')" >
                      <el-icon><plus /></el-icon>
                      <span>添加子类型</span>
                    </div>
                    <div class="tip-item" @click="updataTemType" >
                      <el-icon><edit /></el-icon>
                      <span>修改</span>
                    </div>
                    <div class="tip-item" @click="deleteTemType" >
                      <el-icon><delete /></el-icon>
                      <span>删除</span>
                    </div>
                  </div>
                  
                </template>
              </zdialog>

              <!-- 模板类型框 -->
              <zdialog :title="titleType" @handleClose="closeDialog" v-model="dialogModelTypeVisible" :btnData="dialogBtnData">
                <template #body>
                  <div class="flex-wrap">
                    <div class="leftToRight-layout" style="width: 100%">
                      <div class="label" style="width: 120px;">
                        <span>模板类型名称</span>
                      </div>
                      <div class="operations">
                        <el-input  v-model="modelTypeName" ></el-input>
                      </div>
                    </div>
                  </div>
                  
                </template>
            </zdialog>
            </div>
          </div>
        </div>
      </div>
      </template>



      <!-- <div v-if="isActive === '牙齿检查'">
          <el-empty description="暂无数据"></el-empty>
      </div>
      <div v-if="isActive === '牙周检查'">
        <el-empty description="暂无数据"></el-empty>
      </div>
      <div v-if="isActive === '治疗计划'">
        <el-empty description="暂无数据"></el-empty>
      </div> -->


    </div>
  </div>
  
</template>

<script lang="ts">
import { CaretBottom, Plus, Delete, Edit, ArrowDown } from '@element-plus/icons-vue'
import { defineComponent, reactive, ref, toRefs, onMounted, toRef, watch, nextTick } from "@vue/runtime-core";

import tdialog from "../details/components/recordTemplate.vue"
import zcompose, { ToothList, ToothData } from "../../../components/compose/compose.vue"
import zinput from "./components/zinput.vue"
import zdialog from "../../../components/dialog/dialog.vue"

import recordlist from "./medical/recordList.vue"
import { getFullToothData } from "../../../usefn/getToothData"
import { getNowDate } from "../../../utils/nowDate"

import { getDoctorListAllAPi, getNurseListAllAPi } from "../../../api/common";

import useRequet, { RespData } from "../../../hook/network"
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router';

type OptionType = {
  id: string | number,
  name: string,
}

type TreeData = {
  id: number,
  label: string,
  other?: object,
  children: TreeData[],
  modelList: TreeData[],
  isType: boolean
}
export default defineComponent({
  name: 'MedicalRecord',
  components: {
    tdialog,
    zcompose,
    zinput,
    zdialog,
    recordlist,

    CaretBottom, Plus, Delete, Edit, ArrowDown,
  },
  setup(props) {
    const route = useRoute()
    let id: any = ref(route.params.id)
    watch(() => route.params.id, (newID, prevId) => {
      console.log('执行了,', newID)
      id.value = newID
      
      switchBtn(isActive.value)
    })
    const request = useRequet({ path: "" });
    
    const allTag = ref('')
    const allOptions = ref([] as OptionType[])
    const isActive = ref('病历档案')
    const loading = ref(false)
    const refRecordList: any = ref(null)

    const switchBtn = async(type: string) => {
      switch (type) {
        case '病历档案':
          isActive.value = type
          isAdd.value = false
          await nextTick()
          loading.value = true
          refRecordList.value && refRecordList.value.getList()
          refRecordList.value && refRecordList.value.getLabel()
          loading.value = false
          break;
        case '牙齿检查':
          isActive.value = type
          isAdd.value = false
          break;
        case '牙周检查':
          isActive.value = type
          break;
        case '治疗计划':
          isActive.value = type
          break;
        default:
          break;
      }
    }
    onMounted(() => {
      switchBtn(isActive.value)
    })


    const zhusu = ref(null)
    const kouqiangjiancha = ref(null)

    type Doctors = {
      id: number,
      name: string,
      status?: string
    }

    const recordLength = (len: number) => {
      console.log('书写病历长度', len)
      type.value = len > 0 ? '复诊' : '初诊'
    }

    // 新建病历相关
    const isAdd = ref(false)
    const type = ref('初诊')
    const addMedical = reactive({
      doctor: Number(window.localStorage.getItem('doctorId')) || '',
      doctorOptions: [] as Doctors[],
      nurse: '',
      nurseOptions: [] as Doctors[],
      dateTime: getNowDate(),
    })

    const addRecord = () => {
      isAdd.value = true 
      isActive.value = ''
      // 获取 医生 护士
      getDoctorListAll()
      getNurseListAll()
      getLabel()
    }

    // 病历模板数据
    const treeData = ref([] as TreeData[])
    const getTemTypeList = () => {
      treeData.value = []
      request.sendRequest({
        address: 'sick/history/getCompanyTypeModel',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          let list = resp.data
          recursionTree(list)
          
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
        },
        method: "GET",
      })
    }
    getTemTypeList()
    const recursionTree = (arr: any[]) => {
      // 遍历最外层
      arr.forEach((i:any, index: number) => {
        // 往树形结构中添加数据
        // isType: true 代表是模板类型
        treeData.value.push({
            id: i.id,
            label: i.name,
            children: [],
            modelList: [],
            isType: true
        })
        // 有子类型的 处理
        // 第一层模板类型数据
        i.children.forEach((j: any, idx: number) => {

          treeData.value[index].children.push({
            id: j.id,
            label: j.name || j.title,
            other: j.other,
            children: [],
            modelList: [],
            isType: true
          })
          // 第二层的 模板类型数据
          if(j.children.length > 0) {
            j.children && j.children.forEach((v:any, i: number) => {
              
              treeData.value[index].children[idx].children.push({
                id: v.id,
                label: v.name,
                children: [],
                modelList: [],
                isType: true
              })

              // 第三层的 模板数据
              if(v.modelList.length > 0) {
                v.modelList && v.modelList.forEach((t: any) => {

                  treeData.value[index].children[idx].children[i].children.push({
                    id: t.id,
                    label: t.title,
                    children: [],
                    modelList: [],
                    other: t.other,
                    isType: false
                  })
                })
              }

            })
          }
          // 第二层的 模板数据
          if(j.modelList.length > 0) {
            j.modelList && j.modelList.forEach((v:any, i: number) => {
              
              treeData.value[index].children[idx].children.push({
                id: v.id,
                label: v.title,
                children: [],
                modelList: [],
                other: v.other,
                isType: false
              })

              
            })
            
          }
          
        })
        // 该类型下的模板数据
        // isType: false 代表是模板数据
        // 第一层 模板数据
        i.modelList && i.modelList.forEach((m: any) => {
          treeData.value[index].children.push({
            id: m.id,
            label: m.title,
            children: [],
            modelList: [],
            other: m.other,
            isType: false
          })
        })
        
      })
      
    }


    const isDoctor = (id:number) => {
      let have = false;
      let res = addMedical.doctorOptions.filter(item => {
        return item.id == id
      })

      if(res.length > 0) {
        have = true
      }

      return have;
    }
    const getDoctorListAll = async() => {
      // 获取医生
      let res:any = await getDoctorListAllAPi({});
      if(res.code !== 0) return ElMessage.error(res.msg || '获取信息失败')
          addMedical.doctorOptions = res.data || [];
          let doctorObj = window.localStorage.getItem('doctor')
          let id = JSON.parse(doctorObj!).id;
          
          if(id && !isDoctor(id)) {
            addMedical.doctorOptions.push(JSON.parse(doctorObj!))
          }
    }
    // 获取护士
    const getNurseListAll = async() => {
      let res:any = await getNurseListAllAPi({});
      if(res.code !== 0) return ElMessage.error(res.msg || '获取信息失败')
          addMedical.nurseOptions = res.data || []
    }

    const isOpenChild = ref(false)

    const collapseData = reactive([
      {
        title:'主诉及病史',
        isActive: false,
        children:[
          {
            title:'主诉',
            id: 'zhusu'
          },
          {
            title:'现病史',
            id: 'xianbingshi'
          },
          {
            title:'既往史',
            id: 'jiwangsi'
          }
        ]
      },
      {
        title:'口腔检查',
        isActive: false,
        children:[
          {
            title:'口腔检查',
            id: 'kouqiangjiancha'
          },
          {
            title:'辅助检查',
            id: 'fuzhujiancha'
          },
          {
            title:'相关影像',
            id: '',
          }
        ]
      },
      {
        title:'诊断与治疗计划',
        isActive: false,
        children:[
          {
            title:'诊断',
            id: 'zhenduan',
          },
          {
            title:'治疗计划',
            id:'zhiliaojihua',
          }
        ]
      },
      {
        title:'处置与医嘱',
        isActive: false,
        children:[
          {
            title:'处置',
            id: 'chuzhi'
          },
          {
            title:'医嘱',
            id: 'yizhu'
          }
        ]
      },
      {
        title:'其他',
        isActive: false,
        children:[
          {
            title:'标签'
          },
          {
            title:'备注',
            id: ''
          }
        ]
      }
    ])
    const openChild = (item: any) => {
      collapseData.forEach(i => {
        if(i.title === item.title) {
          i.isActive = !item.isActive
        }
      })
    }

    // const clickItem = (val: object) => {
    //   console.log(val)
    // }
    // 选中模板回显数据
    const selectEchoData = reactive({
      zhusuVal: '',
      xianbingshiVal: '',
      jiwangsiVal: '',
      yizhuVal: ''
    })
    const remarks = ref('')
    const actionChief = ref('')

    const labelList = ref([] as OptionType[])
    const label = ref('')
    const isShow = ref(false)
    const tDialogRef: any = ref(null)
    const showDialog = () => {
      isShow.value = true
      // getTemType()
    }

    // 获取标签
    const getLabel = () => {
      request.sendRequest({
        address: 'sick/history/getMedicalHistoryLabel',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          labelList.value = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      }) 
    }

    type DataTemContent = {
      title: string,
      content: string
    }
    const hideDialog = (data: DataTemContent[], check: boolean) => {
      if(check) {
        data.forEach(item => {
          if(item.title === '主诉') {
            selectEchoData.zhusuVal = item.content
          }
          if(item.title === '现病史') {
            selectEchoData.xianbingshiVal = item.content
          }
          if(item.title === '既往史') {
            selectEchoData.jiwangsiVal = item.content
          }
          if(item.title === '口腔检查') {
            ToothList.value[0].val = item.content
          }
          if(item.title === '辅助检查') {
            ToothList1.value[0].val = item.content
          }
          if(item.title === '治疗计划') {
            ToothList3.value[0].val = item.content
          }
          if(item.title === '诊断') {
            ToothList2.value[0].val = item.content
          }
          if(item.title === '处置') {
            ToothList4.value[0].val = item.content
          }
          if(item.title === '医嘱') {
            selectEchoData.yizhuVal = item.content
          }
          if(item.title === '备注') {
            remarks.value = item.content
          }
        })
      }
      
      isShow.value = false

      // console.log(selectEchoData.zhusuVal)
    }

    

    const ToothList = ref([getFullToothData()] as ToothList[])
    const ToothList1 = ref([getFullToothData()] as ToothList[])
    const ToothList2 = ref([getFullToothData()] as ToothList[])
    const ToothList3 = ref([getFullToothData()] as ToothList[])
    const ToothList4 = ref([getFullToothData()] as ToothList[])
    // 添加牙位
    const addToothPosition = (data:any) => {
      console.debug('点击了添加牙位', data)
      let obj = getFullToothData(true)
      data.push(obj)
    }

    const getLeftData = (leftData: ToothData[], index: number) => {
      
      ToothList.value[index].Tleft = leftData
    }
    const getLeftData1 = (leftData: ToothData[], index: number) => {
      ToothList1.value[index].Tleft = leftData
    }
    const getLeftData2 = (leftData: ToothData[], index: number) => {
      ToothList2.value[index].Tleft = leftData
    }
    const getLeftData3 = (leftData: ToothData[], index: number) => {
      ToothList3.value[index].Tleft = leftData
    }
    const getLeftData4 = (leftData: ToothData[], index: number) => {
      ToothList4.value[index].Tleft = leftData
    }

    const getRightData = (leftData: ToothData[], index: number) => {
      ToothList.value[index].Tright = leftData
    }
    const getRightData1 = (leftData: ToothData[], index: number) => {
      ToothList1.value[index].Tright = leftData
    }
    const getRightData2 = (leftData: ToothData[], index: number) => {
      ToothList2.value[index].Tright = leftData
    }
    const getRightData3 = (leftData: ToothData[], index: number) => {
      ToothList3.value[index].Tright = leftData
    }
    const getRightData4 = (leftData: ToothData[], index: number) => {
      ToothList4.value[index].Tright = leftData
    }

    const getLeftBottomData = (leftData: ToothData[], index: number) => {
      ToothList.value[index].Bleft = leftData
    }
    const getLeftBottomData1 = (leftData: ToothData[], index: number) => {
      ToothList1.value[index].Bleft = leftData
    }
    const getLeftBottomData2 = (leftData: ToothData[], index: number) => {
      ToothList2.value[index].Bleft = leftData
    }
    const getLeftBottomData3 = (leftData: ToothData[], index: number) => {
      ToothList3.value[index].Bleft = leftData
    }
    const getLeftBottomData4 = (leftData: ToothData[], index: number) => {
      ToothList4.value[index].Bleft = leftData
    }

    const getRightBottomData = (leftData: ToothData[], index: number) => {
      ToothList.value[index].Bright = leftData
    }
    const getRightBottomData1 = (leftData: ToothData[], index: number) => {
      ToothList1.value[index].Bright = leftData
    }
    const getRightBottomData2 = (leftData: ToothData[], index: number) => {
      ToothList2.value[index].Bright = leftData
    }
    const getRightBottomData3 = (leftData: ToothData[], index: number) => {
      ToothList3.value[index].Bright = leftData
    }
    const getRightBottomData4 = (leftData: ToothData[], index: number) => {
      ToothList4.value[index].Bright = leftData
    }

    const templateModel = ref({} as any)
    const AddModel = ref({
    } as any)
    const getZhusu = (val: string) => {
      selectEchoData.zhusuVal = val
      templateModel['主诉'] = val
      AddModel.value['主诉'] = val
      actionChief.value = val
    }
    const getXianbs = (val: string) => {
      selectEchoData.xianbingshiVal = val
      templateModel['现病史'] = val
      AddModel.value['现病史'] = val
    }
    const getjiwangs = (val: string) => {
      selectEchoData.jiwangsiVal = val
      templateModel['既往史'] = val
      AddModel.value['既往史'] = val
    }
    const getyizhu = (val: string) => {
      selectEchoData.yizhuVal = val
      templateModel['医嘱'] = val
      AddModel.value['医嘱'] = val
    }


    const changValue = (val: string, index: number) => {
      ToothList.value[index].val = val
    }
    const changValue1 = (val: string, index: number) => {
      ToothList1.value[index].val = val
    }
    const changValue2 = (val: string, index: number) => {
      ToothList2.value[index].val = val
    }
    const changValue3 = (val: string, index: number) => {
      ToothList3.value[index].val = val
    }
    const changValue4 = (val: string, index: number) => {
      ToothList4.value[index].val = val
    }
    const handleDelete = (data:any, index: number) => {
      data.splice(index, 1)
    }


    const save = () => {
      // templateModel['口腔检查'] = ToothList.value[0].val
      // templateModel['辅助检查'] = ToothList1.value[0].val
      // templateModel['诊断'] = ToothList2.value[0].val
      // templateModel['治疗计划'] = ToothList3.value[0].val
      // templateModel['处置'] = ToothList4.value[0].val
      // templateModel['备注'] = remarks.value

      AddModel.value['口腔检查'] = ToothList.value
      AddModel.value['辅助检查'] = ToothList1.value
      AddModel.value['诊断'] = ToothList2.value
      AddModel.value['治疗计划'] = ToothList3.value
      AddModel.value['处置'] = ToothList4.value
      AddModel.value['备注'] = remarks.value

      AddModel.value['主诉'] = selectEchoData.zhusuVal,
      AddModel.value['现病史'] = selectEchoData.xianbingshiVal,
      AddModel.value['既往史'] = selectEchoData.jiwangsiVal,
      AddModel.value['医嘱'] = selectEchoData.yizhuVal


      actionChief.value = selectEchoData.zhusuVal
      if(!addMedical.doctor) {
        ElMessage.warning('请选择医生')
        return
      }
      if(!actionChief.value) {
        ElMessage.warning('请输入主诉')
        return
      }
      // if(label.value.length <= 0) {
      //   ElMessage.warning('请选择标签')
      //   return
      // }
      if(addMedical.doctor && actionChief.value) {
        request.sendRequest({
        address: 'sick/history/addMedicalHistory',
        params: {
          customerId: Number(id.value),
          type: type.value,
          doctorId: addMedical.doctor,
          nurseId: addMedical.nurse,
          seeDoctorTime: addMedical.dateTime,
          labelIdsShow: label.value,
          remark: remarks.value,
          other: AddModel.value,
          actionChief: actionChief.value
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          ElMessage.success('添加成功')
          // 清空病历
          resetTemplate()

          // 添加成功去消息
          isActive.value = '病历档案'
          switchBtn(isActive.value)
          isAdd.value = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
      }
      
    }

    // 重置病历
    const resetTemplate = () => {
      addMedical.dateTime = ''
      label.value = ''
      remarks.value = ''
      actionChief.value = ''
      
      selectEchoData.zhusuVal = '',
      selectEchoData.xianbingshiVal = '',
      selectEchoData.jiwangsiVal = '',
      selectEchoData.yizhuVal = ''

      ToothList.value.forEach(i => i.val = '')
      ToothList1.value.forEach(i => i.val = '')
      ToothList2.value.forEach(i => i.val = '')
      ToothList3.value.forEach(i => i.val = '')
      ToothList4.value.forEach(i => i.val = '')
      
    }

    // 另存为模板部分
    let temObj = ref([
      {
        name: '主诉',
        value: '',
      },
      {
        name: '现病史',
        value: '',
      },
      {
        name: '既往史',
        value: '',
      },
      {
        name: '口腔检查',
        value: '',
      },
      {
        name: '辅助检查',
        value: '',
      },
      {
        name: '诊断',
        value: '',
      },
      {
        name: '治疗计划',
        value: ''
      },
      {
        name: '处置',
        value: '',
      },
      {
        name: '医嘱',
        value: '',
      }
    ])
    let dialogVisible = ref(false)
    // 另存为
    const addTemplate = () => {
      dialogVisible.value = true

      temObj.value.forEach(i => {
        switch(i.name) {
          case '主诉':
            i.value = templateModel['主诉'] || ''
            break;
          case '现病史':
            i.value = templateModel['现病史'] || ''
            break;
          case '既往史':
            i.value = templateModel['既往史'] || ''
            break;
          case '口腔检查':
            i.value = ToothList.value[0].val
            break;
          case '辅助检查':
            i.value = ToothList1.value[0].val
            break;
          case '诊断':
            i.value = ToothList2.value[0].val
            break;
          case '治疗计划':
            i.value = ToothList3.value[0].val
            break;
          case '处置':
            i.value = ToothList4.value[0].val
            break;
          case '医嘱':
            i.value = templateModel['医嘱'] || ''
            break;
        }
      })
    }
    const closeDialog = () => {
      dialogVisible.value = false
      dialogModelTypeVisible.value = false
    }

    const defaultProps = {
      children: 'children',
      label: 'name',
      isLeaf: 'leaf'
    }
    const handleNode = (data: any, node: any) => {
      menuVisbile.value = false
      typeId.value = data.id
      orderNum.value = data.orderNum
    }

    const dialogBtnData = [
      {
        name: '取消',
				func: (data:object) => {
					console.debug('取消',JSON.parse(JSON.stringify(data)))
          dialogModelTypeVisible.value = false
          menuVisbile.value = false
				}
      },
      {
        name: '保存',
        func: (data:object) => {
					console.debug('保存',JSON.parse(JSON.stringify(data)))
            menuVisbile.value = false
            if(titleType.value === '添加模板根类型' || titleType.value === '添加模板子类型') {
                if(modelTypeName.value) {
                    addModelTypeTree()
                  }
              
            }
            if(titleType.value === '修改模板类型') {
              updateModelTypeTree()
            }
            
				}
      }
    ]
    
    const titleType = ref('添加模板根类型')
    const dialogModelTypeVisible = ref(false)
    const modelTypeName = ref('')
    const parentId = ref(0)
    const orderNum = ref('')
    const tipsOPerRef = ref<HTMLElement | null>(null)
    const menuVisbile = ref(false)
    // 点击某一节点右击事件
    const handleNodeMenu = (e: MouseEvent, obj: any, node: any) => {

      orderNum.value = obj.orderNum
      parentId.value = obj.id
      modelTypeName.value = obj.name

      menuVisbile.value = true
      // // 获取鼠标右击的 x, y 坐标
      let x = e.clientX;
      let y = e.clientY;
      (tipsOPerRef.value as HTMLElement).style.top = y + 10 +  'px';
      (tipsOPerRef.value as HTMLElement).style.left = x + 20 + 'px';

    }
    // 模板类型
    type templateList = {
      name: string,
      isEdit: boolean
    }
    const typeId = ref('')
    const temTitle = ref('')
    const isEdit = ref(false)
    const templateType = ref('')
    const templateList = ref([] as templateList[])
    const templateListRef = ref<any>(null)
    const getTemType = () => {
      request.sendRequest({
        address: 'sick/history/getCompanyTypeTree',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          templateList.value = resp.data
          // templateList.value.forEach(item => {
          //   item.isEdit = false
          // })
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
        },
        method: "GET",
      })
    }
    getTemType()
   
    // 单元格选择
    const handleSelectionChange = (val:any) => {

      if(val.length > 1) {
        templateListRef.value.clearSelection()
        templateListRef.value.toggleRowSelection(val.pop())
      } else {
        if(val.length) {
          typeId.value = val[0].id
        }

        
      }
    }
    const addTemType = (type: string) => {
      dialogModelTypeVisible.value = true
      modelTypeName.value = ''
      if(type === 'root') {
        // 根
        titleType.value = '添加模板根类型'
        parentId.value = 0
      }
      if(type === 'children') {
        // 子
        titleType.value = '添加模板子类型'
      }
      
    }
    const addModelTypeTree = () => {
      request.sendRequest({
          address: 'sick/history/addModelType',
          params: {
            name: modelTypeName.value,
            orderNum: orderNum.value,
            parentId: parentId.value
          },
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            modelTypeName.value = ''
            dialogModelTypeVisible.value = false
            getTemType()
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
          },
          method: "POST",
        })
    }
    const updataTemType = () => {
      dialogModelTypeVisible.value = true
      titleType.value = '修改模板类型'
    }
    const updateModelTypeTree = () => {
      request.sendRequest({
        address: 'sick/history/updateModelType',
        params: {
          id: parentId.value,
          name: modelTypeName.value,
          orderNum: orderNum.value,
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          modelTypeName.value = ''
          dialogModelTypeVisible.value = false
          getTemType()
          
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
        },
        method: "POST",
      })
    }
    const deleteTemType = () => {
      // let id = val.id
      menuVisbile.value = false
      ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        request.sendRequest({
          address: `sick/history/delModelType/${parentId.value}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            getTemType()
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
          },
          method: "POST",
        })
      }).catch(() => {
            ElMessage({
              type: 'info',
              message: '已取消删除',
            });
        })

    }

    const btnData = [
      {
        name: '取消',
				func: (data:boolean) => {
							console.debug('取消',data)
              closeDialog()
				}
      },
      {
        name: '保存',
				func: (data:boolean) => {
							console.debug('保存',data, temObj)
              let templateModelObj = {}
              temObj.value.forEach(i => {
                templateModelObj[i.name] = i.value
              })
              // templateModel['口腔检查'] = ToothList.value[0].val
              // templateModel['辅助检查'] = ToothList1.value[0].val
              // templateModel['诊断'] = ToothList2.value[0].val
              // templateModel['治疗计划'] = ToothList3.value[0].val
              // templateModel['处置'] = ToothList4.value[0].val
              // templateModel['备注'] = remarks.value

              if(!typeId.value) {
                ElMessage.warning('请选择模板类型')
                return
              } else if (!temTitle.value) {
                ElMessage.warning('请输入模板名称')
                return
              } else {
                request.sendRequest({
                    address: 'sick/history/addModel',
                    params: {
                      typeId: typeId.value,
                      title: temTitle.value,
                      orderNum: orderNum.value,
                      other: templateModelObj
                    },
                    success: (resp: RespData) => {
                      if(resp.code !== 0) return ElMessage.error(resp.msg)
                      closeDialog()
                    },
                    fail: (resp: RespData) => {
                      if(resp.code !== 0) return ElMessage.error(resp.msg)
                    },
                    method: "POST",
                  })
              }
				}
      }
    ]

    // 打印所有病历
    const handleAllParint = () => {
      ElMessage('功能还在完善,敬请期待......');
    }

    // 新建病历 取消
    const cancel = () => {
      ElMessage('功能还在完善,敬请期待......');
    }

    
    return {
      id,
      allTag,
      allOptions,
      isActive,
      loading,
      tDialogRef,
      switchBtn,

      treeData, // 给模板数据给输入框
      recordLength,

      zhusu,
      kouqiangjiancha,
      refRecordList,

      isAdd,
      type,
      ...toRefs(addMedical),

      isOpenChild,
      collapseData,
      openChild,
      // clickItem,
      addRecord,

      isShow,
      showDialog,
      hideDialog,

      label,
      labelList,
      ...toRefs(selectEchoData),
      defaultProps,
      handleNode,
      handleNodeMenu,
      tipsOPerRef,
      menuVisbile,
      parentId,
      orderNum,
      dialogBtnData,
      titleType,
      dialogModelTypeVisible,
      modelTypeName,

      
      remarks,
      temObj, // 另存为模板

      getLeftData,
      getLeftData1,
      getLeftData2,
      getLeftData3,
      getLeftData4,

      getRightData,
      getRightData1,
      getRightData2,
      getRightData3,
      getRightData4,

      getLeftBottomData,
      getLeftBottomData1,
      getLeftBottomData2,
      getLeftBottomData3,
      getLeftBottomData4,

      getRightBottomData,
      getRightBottomData1,
      getRightBottomData2,
      getRightBottomData3,
      getRightBottomData4,

      addToothPosition,
      AddModel,
      templateModel,
      getZhusu,
      getXianbs,
      getjiwangs,
      getyizhu,
      changValue,
      changValue1,
      changValue2,
      changValue3,
      changValue4,
      handleDelete,
      ToothList,
      ToothList1,
      ToothList2,
      ToothList3,
      ToothList4,

      save,

      addTemplate,
      dialogVisible,
      btnData,
      closeDialog,
      templateList,
      templateListRef,
      addTemType,
      templateType,
      updataTemType,
      handleSelectionChange,
      deleteTemType,
      temTitle,
      typeId,
      isEdit,

      handleAllParint,
      cancel
    }
  },
  methods: {
    

    clickItem (c: any) {
      let ref = c.id
      
        if(ref) {
          
          if(c.title === '口腔检查') {
            (this.$refs as any)[ref].zinputdom.focus()
          } else if (c.title === '辅助检查') {
            (this.$refs as any)[ref].zinputdom.focus()
          } else if (c.title === '治疗计划') {
            (this.$refs as any)[ref].zinputdom.focus()
          } else if (c.title === '诊断') {
            (this.$refs as any)[ref].zinputdom.focus()
          } else if (c.title === '处置') {
            (this.$refs as any)[ref].zinputdom.focus()
          } else {
            (this.$refs as any)[ref].$refs.inputfocus.focus()
          }
          

          let position: any =  (this.$refs as any)[ref].$refs.zinput.offsetTop;
          (this.$refs.scrooll as any).scrollTo(0, position)
        }
    }
  }

})
</script>

<style lang="scss" scoped>
@import "@style/extend";
.medical-record {
  display: flex;
  flex-direction: column;
  height: 100%;

  .medical-head {
    height: 40px;
    line-height: 40px;
    display: flex;
    background: $a2-Color;
    border-bottom: 1px solid $mainColor;
    .head-left {
      font-size: $fontSize-1;
      & > span {
        padding: 10px 20px;
        cursor: pointer;
        position: relative
      }

      & > span::before {
        content: '';
        width: 1px;
        height: 100%;
        background: $a10-Color;
        position: absolute;
        right: 0;
        transform: scaleY(.5);
      }
    }
    .head-right {
      flex: 1;
      text-align: right;
      padding-right: 20px;

      .adjustment {
        display: inline-block;
        padding-right: 15px;
      }
    }
  }
  .medical-content {
    box-sizing: border-box;
    padding: 10px 20px;
    flex: 1;
    overflow: auto;
    .medical-one {
      height: 100%;
      // display: flex;
      
    }
    

    .medical-add {
      .title-border {

        .title {
          @extend .standard-4;
          border-bottom: 1px solid $mainColor;
          height: 40px;
          line-height: 40px;
          position: relative;
          span {
            padding-left: 10px;
          }
        }
        .title::before {
          content: '';
          display: block;
          width: 2px;
          height: 100%;
          background: $mainColor;
          position: absolute;
          transform: scaleY(.6);
        }

        .t-content {
          padding: 10px;
          display: flex;
          .ware-type {
            @extend .standard-1;
            padding-right: 20px;
            .type-title {
              padding-bottom: 5px;
              font-weight: 600;
            }
          }

          .left-switch {
            border: 1px solid #ccc;
            // height: 200px;
            width: 180px;
            box-sizing: border-box;
            .collapse {
              width: 100%;
              .collapse-child {
                .open {
                  width: 100%;
                  height: 30px;
                  line-height: 30px;
                  @extend .standard-4;
                  cursor: pointer;
                  padding-left: 10px;
                  box-sizing: border-box;
                }
                ul > li {
                  font-size: 14px;
                  padding: 5px 25px;
                  cursor: pointer;
                }
                ul > li:hover {
                  background: $mainColor;
                  color: white;
                }
              }
            }
          }

          .right-info {
            // background: blue;
            width: calc(100% - 150px);
            margin-left: 20px;

            .template-medical {
              width: 100%;
              height: 30px;
              line-height: 30px;
              border: 1px solid $mainColor;
              border-radius: $radius-1;
              box-sizing: border-box;
              text-align: center;
              font-size: $fontSize-1;
              color: $mainColor;
              cursor: pointer;
            }

            .main-foo {
              line-height: 45px;
              text-align: right;
            }

            .scrooll {
              height: 500px;
              overflow-y: auto;
              position: relative;
              box-sizing: border-box;
            }
          }
        }
      }
    }
  }
    
}

.temp-Type {
  display: flex;
  overflow-y: auto;
  position: relative;

  .left-tree-Type {
    flex: 1;
    // background-color: red;
    background-color: white;
    display: flex;
    flex-direction: column;

    .tree-title {
      height: 45px;
      line-height: 45px;
      width: 100%;
      background-color: $mainColor;
      color: white;
      text-align: center;
    }

    .tree-mian {
      flex: 1;
      overflow-y: auto;
    }

    .tree-footer {
      height: 45px;
      line-height: 45px;
      background-color: white;
      color: $mainColor;
      cursor: pointer;
      text-align: center;
      box-shadow: 0 2px 8px #ccc;
    }
  }

  .right-temp-content {
    flex: 3;
    // background-color: #ececec;
    border-left: 1px solid #ccc;
  }
}

ul {
  margin: 0;
  padding: 0;
}
ul > li {
  list-style: none;
  // padding-left: 0;
  margin: 0;
}

.type-title {
  padding-left: 10px;
}
.type-content {
  padding: 0 10px;
  display: flex;
  .width200 {
    width: 200px;
  }
}

.text-layout {
  display: flex;
  width: 260px;
  height: 35px;
  line-height: 35px;
  padding-left: 10px;
  border-bottom: 1px dashed #e9e9e9;
  margin: 5px 0;
  padding-top: 5px;
  .text {
    flex: 1;
  }
  .operation {
    display: flex;
    & > span {
      cursor: pointer;
    }
    & > span:nth-child(1) {
      padding: 0 8px;
    }
  }
}

.tipsOperation {
  background: white;
  min-width: 100px;
  // height: 80px;
  box-shadow: 0 2px 4px #ccc;
  border-radius: 4px;
  position: fixed;
  z-index: 99;
  .tip-item {
    line-height: 35px;
    // text-align: center;
    cursor: pointer;
    padding-left: 15px;

    & > span {
      font-size: 14px;
      padding-left: 5px;
    }
  }
  .tip-item:hover {
    background: #e9e9e9;
  }
}

.active {
  background: $mainColor;
  color: white;
}

.hide {
  display: none;
}
</style>